import requests, json, re, os, sys
from django.core.mail import send_mail

sys.path.append(os.path.abspath('.') + '/Test_Ayl')
sys.path.append(os.path.abspath('.') + '/Test_Ayl/')

os.environ['DJANGO_SETTINGS_MODULE'] = 'Test_Ayl.settings'

ipconfig = os.popen("ipconfig")

ipconfig_list = [i.split("\n") for i in ipconfig]
if ipconfig_list[8] != ['', '']:
    ipconfig = ipconfig_list[8]
else:
    ipconfig = ipconfig_list[-3]

proxies = {"https": f"{ipconfig[0].split(':')[-1].replace(' ', '')}:8888"}
print(f"当前电脑IP: {proxies}")


class Dict(dict):
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__


def dict_to_object(dictObj):
    if not isinstance(dictObj, dict):
        return dictObj
    inst = Dict()
    for k, v in dictObj.items():
        inst[k] = dict_to_object(v)
    return inst


class Core():  # 核心复用方法

    def __init__(self):
        pass

    def send_mail(self, content):
        sender = '122903166@qq.com'
        Subject = '来自www.douchacha.com的警告邮件'
        receiver = ['diao.guanguan@aiyingli.com', '642229662@qq.com', 'juncai.xu@aiyingli.com',
                    'zhiming.ren@aiyingli.com', 'chao.chen@aiyingli.com']
        send_mail(Subject, content, sender, receiver, )
        pass

    def pass_mail(self, content, mail):
        sender = '122903166@qq.com'
        Subject = '来自www.douchacha.com的结果邮件'
        receiver = []
        receiver.append(mail)
        send_mail(Subject, content, sender, receiver, )
        pass

    # def yellowlab(self, url):
    #     yellowlaburl = 'https://yellowlab.tools/api/runs'
    #     yellow = requests.Session()
    #     payload = {
    #         "url": url,
    #         "waitForResponse": False,
    #         "screenshot": True,
    #         "device": "desktop"
    #     }
    #     header = {
    #         "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
    #         "content-type": "application/json;charset=UTF-8",
    #         "sec-fetch-site": "same-origin",
    #         "sec-fetch-mode": "cors",
    #         "sec-fetch-dest": "empty"}
    #     response = yellow.post(yellowlaburl, data=json.dumps(payload), headers=header, verify=False)
    #     yellowlaburl = 'https://yellowlab.tools/api/runs/%s' % response.json()['runId']
    #     header = {
    #         "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
    #         "sec-fetch-site": "same-origin",
    #         "sec-fetch-mode": "cors",
    #         "sec-fetch-dest": "empty"
    #     }
    #     response = yellow.post(url=yellowlaburl, headers=header, verify=False)
    #     runId = response.json()['runId']
    #     return runId
    def yellowlab(self, url):
        yellowlaburl = 'https://yellowlab.tools/api/runs'
        yellow = requests.Session()
        payload = {
            "url": url,
            "waitForResponse": False,
            "screenshot": True,
            "device": "desktop"
        }
        header = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
            "content-type": "application/json;charset=UTF-8",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty"}
        response = yellow.post(yellowlaburl, data=json.dumps(payload), headers=header, proxies=proxies, verify=False)
        yellowlaburl = 'https://yellowlab.tools/api/runs/%s' % response.json()['runId']
        header = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
            "sec-fetch-site": "same-origin",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty"
        }
        response = yellow.get(url=yellowlaburl, headers=header, proxies=proxies, verify=False)
        runId = response.json()['runId']
        return runId

    def inerface_contrast(self, contrast, parsing, expected_value):  # ---------------------检查接口返回参数
        par_value_temp = None
        expected_value_temp = None
        parsin = None
        expected = None
        error = []
        loc = locals()
        try:
            for key in contrast:
                exec("par_value_temp = parsing%s" % key)
                parsin = loc['par_value_temp']
                exec("expected_value_temp = expected_value%s" % key)
                expected = loc['expected_value_temp']
                if parsin == expected:
                    error.append(key + ':pass')
                else:
                    error.append(key + ':error')
            return error
        except:
            error.append(key + ":接口没有返回您指定检查得key")
            return error

    def inerface_contraston(self, contrast, parsing, expected_value, url, casename,
                            gonumber):  # ---------------------检查接口返回参数
        par_value_temp = None
        expected_value_temp = None
        parsin = None
        expected = None
        error = []
        loc = locals()
        try:
            for key in contrast:
                exec("par_value_temp = parsing%s" % key)
                parsin = loc['par_value_temp']
                exec("expected_value_temp = expected_value%s" % key)
                expected = loc['expected_value_temp']
                if parsin == expected:
                    error.append(key + ':pass')
                else:
                    error.append(key + ':error')
                    content = "Casename:" + casename + "\n" + "第" + str(
                        gonumber) + "条用例" + "\n" + "接口地址：" + url + "\n" + "错误key：" + key + "\n" + "返回数据：" + "\n" + str(
                        parsing) + "\n" + "预期值：" + "\n" + str(expected_value)
                    self.send_mail(content)
            return error
        except:
            error.append(key + ":接口没有返回您指定检查得key")
            return error

    def onnull(self, contrast, parsing, url):  # ---------------------检查接口返回不为空
        par_value_temp = None
        expected_value_temp = None
        parsin = None
        expected = None
        error = []
        loc = locals()
        try:
            for key in contrast:
                exec("par_value_temp = parsing%s" % key)
                parsin = loc['par_value_temp']
                if parsin != '' and parsin != ' ' and parsin != None and parsin != 'null':
                    error.append(key + ':不为空检查pass')
                else:
                    error.append(key + ':不为空检查error')
                    content = "接口地址：" + url + "\n" + "错误key：" + key + "\n" + "返回数据：" + "\n" + str(
                        parsing) + "\n" + "预期值：不为空"
                    self.send_mail(content)
            return error
        except:
            error.append(key + ":接口没有返回您指定检查得key")
            return error

    def replace(self, keys, Caseheaders, Caseurl, Casebody, Casedeliverlist_s):  # ---------------------检查接口返回参数
        loc = locals()
        for key in keys:
            try:
                if 'header' in key:
                    print(type(Caseheaders))
                    Caseheaders = json.loads(Caseheaders)
                    print(type(Caseheaders))
                    print('json.loads(Caseheaders)', Caseheaders)
                    b = eval("""Casedeliverlist_s['%s']""" % keys[key])
                    aaa = key.replace("['header']:", '')
                    exec('Caseheaders["%s"]=b' % aaa)
                    Caseheaders = loc['Caseheaders']
                elif 'body' in str(key):
                    if len(Casebody) != 0:
                        Casebody = json.loads(Casebody)
                        b = eval("""Casedeliverlist_s['%s']""" % keys[key])
                        aaa = key.replace("['body']:", '')
                        exec('Casebody["%s"]=b' % aaa)
                        Casebody = loc['Casebody']
                        Casebody = json.dumps(Casebody)
                    else:
                        Casebody = None

                elif 'url' in str(key):
                    b = eval("""Casedeliverlist_s['%s']""" % keys[key])
                    url = key.replace("['url']:", '')
                    Caseurl = Caseurl + '?' + '%s' % url + '=' + b
            except:
                pass
        if len(Casebody) != 0:
            Casebody = json.loads(Casebody)
        return json.dumps(Caseheaders), Caseurl, Casebody


if __name__ == "__main__":
    mail = Core()
    content = 'BUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUGBUG'
    mail.send_mail(content)
